<template>
  <el-container>
    <el-aside class="bg-white" width="420px">
      <!--左侧搜索条件-->
      <div class="container-ymm container_tabs pt-20">
        <el-row :gutter="10" class="header-ymm" style="padding:0;border:none;">
          <el-select
            v-model="inventoryStatus"
            placeholder="状态"
            class="seach-select"
            size="small"
            @change="getList"
          >
            <el-option
              v-for="inventoryStatus in inventoryStatusList"
              :label="inventoryStatus.name"
              :value="inventoryStatus.id"
              :key="inventoryStatus.id"
            />
          </el-select>
          <el-select
            v-model="warehouseId"
            placeholder="仓库"
            class="seach-select"
            size="small"
            @change="getList"
          >
            <el-option
              v-for="warehouse in warehouseList"
              :label="warehouse.warehouseName"
              :value="warehouse.warehouseId"
              :key="warehouse.warehouseId"
            />
          </el-select>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="17">
            <el-date-picker
              v-model="listQuery.time"
              :picker-options="pickerOptions"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            />
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="searchFrom">查询</el-button>
          </el-col>
        </el-row>

        <el-row>
          <div class="list">
            <div
              v-for="(item,index) in tableInventoryData"
              :key="index"
              :style="item.Mystyle"
              class="item"
              @click="currentChange(item)"
            >
              <p class="name">{{ item.warehouseName }}</p>
              <el-row type="flex" justify="space-between">
                <span class="price">{{ item.inventoryStatus==='1'?'待盘点':'已盘点' }}</span>
                <span class="date">{{ item.createTime |parseTime('{y}-{m}-{d}') }}</span>
              </el-row>
            </div>
          </div>

          <div class="table-ymm-bt1">
            <el-pagination
              :current-page="listQuery.page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="10"
              :pager-count="listQuery.pageSize"
              :total="total"
              background
              layout="sizes, prev, pager, next,total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <component :is="modal" :modal-data="modalData" @close="closeChild"/>
        </el-row>
      </div>
    </el-aside>
    <el-main>
      <div class="container-ymm" style="margin-left:15px;">
        <div class="pl-30 pr-30">
          <el-row :gutter="10" style="text-align:right" class="pt-15 pb-15">
            <el-col :span="6"/>
            <el-button type="primary" @click="addFun">新建盘点</el-button>

            <el-button
              v-show="checkPermission('pas:inventory:save')"
              type="primary"
              @click="saveInventorySheetAndDetails"
            >保存</el-button>
            <el-button
              v-show="checkPermission('pas:inventory:end')"
              type="primary"
              @click="filishInventorySheetDetailsById"
            >结束</el-button>
            <el-button
              v-show="checkPermission('pas:inventory:export')"
              type="primary"
              @click="doExportInventoryInfo"
            >导出</el-button>
          </el-row>
          <el-row :gutter="20" style="margin-bottom: 15px;border: 1px dashed #eee"/>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-row :gutter="1">
                <el-col :span="6">
                  <div class="shipment_label">盘点单:</div>
                </el-col>
                <el-col :span="17">
                  <div
                    class="shipment_div"
                    style="color:#28A087"
                  >{{ tableInventoryObj.inventoryNumber }}</div>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="6">
              <el-row :gutter="1">
                <el-col :span="6">
                  <div class="shipment_label">创建时间:</div>
                </el-col>
                <el-col :span="17">
                  <div
                    class="shipment_div"
                  >{{ tableInventoryObj.createTime | parseTime() }}</div>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="6">
              <el-row :gutter="1">
                <el-col :span="6">
                  <div class="shipment_label">盘点仓库:</div>
                </el-col>
                <el-col :span="17">
                  <div class="shipment_div">{{ tableInventoryObj.warehouseName }}</div>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="6">
              <el-row :gutter="1">
                <el-col :span="6">
                  <div class="shipment_label">盘点范围:</div>
                </el-col>
                <el-col :span="17">
                  <div v-if="tableInventoryObj.inventoryType==='1'" class="shipment_div">整机</div>
                  <div v-else-if="tableInventoryObj.inventoryType==='2'" class="shipment_div">辅材</div>
                  <div v-else-if="tableInventoryObj.inventoryType==='3'" class="shipment_div">工具</div>
                  <div v-else-if="tableInventoryObj.inventoryType==='4'" class="shipment_div">赠品</div>
                  <div v-else class="shipment_div">全部</div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row :gutter="20"/>
        </div>

        <div>
          <div class="table-ymm">
            <el-table :data="tableData" style="width: 100%" height="500" border>
              <el-table-column label="分类">
                <template slot-scope="scope">
                  <spn v-if="scope.row.inventoryType==='1'">整机</spn>
                  <spn v-else-if="scope.row.inventoryType==='2'">辅材</spn>
                  <spn v-else-if="scope.row.inventoryType==='3'">工具</spn>
                  <spn v-else-if="scope.row.inventoryType==='4'">赠品</spn>
                </template>
              </el-table-column>
              <el-table-column label="SKU编码">
                <template slot-scope="scope">
                  <span>{{ scope.row.skuCode }}</span>
                </template>
              </el-table-column>
              <el-table-column label="SKU名称">
                <template slot-scope="scope">
                  <span>{{ scope.row.skuName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="条码">
                <template slot-scope="scope">
                  <span>{{ scope.row.serialNumber }}</span>
                </template>
              </el-table-column>

              <el-table-column label="盘点数量" property="physicalInventory">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.physicalInventory"
                      type="number"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                      @change="number(scope.row)"
                      @keyup.native="number(scope.row)"
                    />
                  </template>
                  <span v-else>{{ scope.row.physicalInventory }}</span>
                </template>
              </el-table-column>

              <el-table-column label="系统库存">
                <template slot-scope="scope">
                  <span>{{ scope.row.systemInventory }}</span>
                </template>
              </el-table-column>
              <el-table-column label="可用库存">
                <template slot-scope="scope">
                  <span>{{ scope.row.availableStock }}</span>
                </template>
              </el-table-column>
              <el-table-column label="盈亏数量">
                <template slot-scope="scope">
                  <span>{{ scope.row.physicalInventory !==null ? scope.row.physicalInventory - scope.row.systemInventory :'--' }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- <div class="table-ymm-bt">
            <el-pagination
              :current-page="table.current_page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="10"
              :pager-count="table.page_count"
              :total="table.total"
              background
              layout="sizes, prev, pager, next,total"
              @current-change="handleCurrentChange"
            />
          </div>
          <component :is="modal" :modal-data="modalData" @close="closeChild"/>-->
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { parseTime } from '@/utils'
import { getUserInfo } from '@/api/login'
import {
  getInventorySheet,
  getInventorySheetDetails,
  saveInventorySheetAndDetails,
  filishInventorySheetDetailsById,
  exportInventoryInfo
} from '@/api/pas/inventory'
import Add from './dialog/Add.vue'
import { queryList } from '@/api/pas/warehouse'
export default {
  data() {
    return {
      listQuery: {
        page: 1,
        pageSize: 10,
        keyword: null,
        starTime: null,
        endTime: null,
        time: null,
        pageNumber: null,
        warehouseId: null,
        inventoryStatus: null
      },
      total: 1,
      warehouseId: null,
      warehouseList: [],
      firstOption: { warehouseId: '', warehouseName: '请选择仓库' },
      inventoryStatus: null,
      inventoryStatusList: [
        { id: null, name: '状态' },
        { id: 1, name: '待盘点' },
        { id: 2, name: '已盘点' }
      ],
      rules: {
        physicalInventory: [
          { required: true, message: '请输入附件总数', trigger: 'change' },
          {
            validator(rule, value, callback) {
              if (Number.isInteger(Number(value)) && Number(value) > 0) {
                callback()
              } else {
                callback(new Error('请输入有效数字'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      modal: null,
      listLoading: true,
      // Mystyle: 'background-color: #c7c0c0',
      userid: null,
      modalData: {},
      inventoryNumber: '', // 盘点单号
      createTime: new Date(), // 创建时间
      warehouseName: '深圳仓', // 盘点仓库
      inventoryType: '整机', // 盘点类型
      tableInventoryObj: {},
      tableData: [],
      tableInventoryData: [],
      table: {
        current_page: 1,
        page_count: 7,
        total: 1
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      time: ''
    }
  },
  created() {
    this.getPermission()
    this.getList()
    this.queryAllWarehouse()
  },
  methods: {
    currentChange(item) {
      this.inventoryNumber = item.inventoryNumber
      this.tableInventoryObj = item
      this.getInventorySheetDetails(item)
      // 选择记录
      for (var i = 0; i < this.tableInventoryData.length; i++) {
        if (this.tableInventoryData[i].Mystyle) {
          this.tableInventoryData[i].Mystyle = null
        }
      }
      item.Mystyle = 'background-color: #c7c0c0'
    },
    // 分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 表格选择
    handleSelectionChange() {},
    closeChild() {
      this.modal = null
      this.getList()
    },
    addFun() {
      this.modalData = { type: '1111' }
      this.modal = Add
    },
    getList() {
      this.listLoading = true
      this.listQuery.pageNumber =
        (this.listQuery.page - 1) * this.listQuery.pageSize
      this.listQuery.warehouseId = this.warehouseId
      this.listQuery.inventoryStatus = this.inventoryStatus
      getInventorySheet(this.listQuery)
        .then(response => {
          if (response.data.status === 'success') {
            if (
              !response.data.data.list ||
              response.data.data.list.length === 0
            ) {
              this.listLoading = false
              this.tableInventoryData = []
              this.tableData = []
              this.tableInventoryObj = []
              this.total = 1
              return
            }
            this.total = response.data.data.total
            this.tableInventoryData = response.data.data.list
            this.tableInventoryObj = this.tableInventoryData[0]
            this.tableInventoryData[0].Mystyle = 'background-color: #c7c0c0'
            this.getInventorySheetDetails(this.tableInventoryData[0])
            this.listLoading = false
          } else if (response.data.status === 'token_check_faild') {
            this.$message({
              message: response.data.messge,
              type: 'warning'
            })
            this.listLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '数据加载失败',
            type: 'warning'
          })
          this.listLoading = false
        })
    },
    getInventorySheetDetails(row) {
      this.listLoading = true
      var flag = true
      if (row.inventoryStatus === '2') {
        flag = false
      }
      var query = {
        inventoryNumber: row.inventoryNumber
      }
      getInventorySheetDetails(query)
        .then(response => {
          if (response.data.status === 'success') {
            if (response.data.data.length === 0) {
              this.listLoading = false
              this.tableData = []
              return
            }

            const items = response.data.data
            this.tableData = items.map(v => {
              this.$set(v, 'edit', flag) // https://vuejs.org/v2/guide/reactivity.html
              return v
            })

            this.listLoading = false
          } else if (response.data.status === 'token_check_faild') {
            this.$message({
              message: response.data.messge,
              type: 'warning'
            })
            this.listLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '数据加载失败',
            type: 'warning'
          })
          this.listLoading = false
        })
    },
    searchFrom() {
      if (this.listQuery.time !== null && this.listQuery.time !== '') {
        this.listQuery.starTime = parseTime(
          this.listQuery.time[0],
          '{y}-{m}-{d} {h}:{i}'
        )
        this.listQuery.endTime = parseTime(
          this.listQuery.time[1],
          '{y}-{m}-{d} {h}:{i}'
        )
      } else {
        this.listQuery.starTime = null
        this.listQuery.endTime = null
      }
      this.listQuery.pageNumber = 0
      this.listQuery.page = 1
      this.getList()
    },
    saveInventorySheetAndDetails() {
      // 提交集合表单
      this.detailsJson = JSON.stringify(this.tableData)
      var formData = new FormData()
      formData.append('detailsJson', this.detailsJson)
      saveInventorySheetAndDetails(formData)
        .then(response => {
          if (response.data.status === 'success') {
            this.$message({
              message: '保存盘点单成功',
              type: 'success'
            })
            setTimeout(() => {
              this.getList()
            }, 1.5 * 1000)
          } else {
            this.$message({
              message: '保存盘点单失败：' + response.data.messge,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    filishInventorySheetDetailsById() {
      // 提交集合表单
      this.detailsJson = JSON.stringify(this.tableData)
      var formData = new FormData()
      formData.append('detailsJson', this.detailsJson)
      filishInventorySheetDetailsById(formData)
        .then(response => {
          if (response.data.status === 'success') {
            this.$message({
              message: '结束盘点单成功',
              type: 'success'
            })
            setTimeout(() => {
              this.getList()
            }, 1.5 * 1000)
          } else {
            this.$message({
              message: '结束盘点单失败：' + response.data.messge,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    doExportInventoryInfo: function() {
      var data = { inventoryNumber: this.tableInventoryObj.inventoryNumber }
      exportInventoryInfo(data).then(response => {
        const date = new Date()
        const filefix =
          date.getFullYear() +
          '-' +
          date.getMonth() +
          '-' +
          date.getDate() +
          ' ' +
          date.getHours() +
          ':' +
          date.getMinutes() +
          ':' +
          date.getSeconds()
        const blob = new Blob([response.data], {
          type: 'text/csvchartset=utf-8' // 将会被放入到blob中的数组内容的MIME类型
        }) // 创建一个blob对象
        const a = document.createElement('a') // 创建一个<a></a>标签
        a.href = URL.createObjectURL(blob) // response is a blob
        a.download = filefix + '盘点明细.csv' // 文件名称
        a.style.display = 'none'
        document.body.appendChild(a)
        a.click()
        a.remove()
        return response
      })
    },
    number(row) {
      // debugger
      if (row.physicalInventory !== 0) {
        row.physicalInventory = Math.abs(row.physicalInventory)
      }
    },
    queryAllWarehouse() {
      var data = {
        deteleFlag: 'N',
        isRange: 'ALL'
      }
      queryList(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.warehouseList = response.data.data.list
            this.warehouseList.unshift(this.firstOption)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getPermission() {
      // debugger
      var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
      for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split('=') // 再次切割
        // 判断查找相对应的值
        if (arr2[0] === 'token') {
          this.userid = arr2[1]
        }
      }
      if (!this.userid || localStorage.getItem(this.userid)) {
        return
      }
      getUserInfo().then(response => {
        if (response.data.status === 'ok') {
          localStorage.setItem(
            this.userid,
            JSON.stringify(response.data.data.permissions)
          )
        }
      })
    },
    checkPermission(value) {
      if (value && this.userid) {
        if (
          localStorage.getItem(this.userid) &&
          localStorage.getItem(this.userid).indexOf(value) >= 0
        ) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    }
  }
}
</script>

<style >
.shipment_label {
  float: left;
  font-family: 'Microsoft Yahei';
  font-size: 16px;
}

.shipment_div {
  float: left;
  font-family: 'Microsoft Yahei';
  font-size: 13px;
  font-weight: 500;
}
.material-filter-container > .el-row,
.shipment_header {
  border: 1px;
  color: #333;
  line-height: 30px;
}

.el-aside {
  color: #333;
  line-height: 18px;
}

.el-main {
  color: #333;
  text-align: center;
  line-height: 30px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-container:nth-child(5) .el-aside {
  line-height: 260px;
}
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}
.el-pagination__total,
.el-pagination__sizes,
.btn-prev,
.el-pager,
.btn-next,
.el-pagination__jump {
  margin-top: 2px !important;
}
.el-pagination {
  line-height: 1px;
  white-space: pre-wrap;
}
.el-table__body tr.current-row > td {
  background-color: #dde9fc;
}

.el-date-editor--datetimerange.el-input,
.el-date-editor--datetimerange.el-input__inner {
  width: 250px;
}
.el-date-editor .el-range-separator {
  display: inline-block;
  height: 100%;
  padding: 0 5px;
  margin: 0;
  text-align: center;
  line-height: 32px;
  font-size: 14px;
  width: 15%;
  color: #303133;
}
.container-ymm .table-ymm-bt1 {
  padding-top: 2rem;
  padding-bottom: 1rem;
}
.item {
  height: 4rem;
}
.list {
  height: 550px;
  overflow: auto;
}
.el-input--small .el-input__inner {
  margin-left: 0.4rem;
  height: 32px;
  line-height: 32px;
}
</style>
